package com.tihi.handsuiviewer;

import ofs.ahd.dii.br.AdSize;
import ofs.ahd.dii.br.AdView;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tihi.floatview.FloatViewMgr;
import com.tihi.ui.base.BaseActivity;
import com.tihi.uiautomator.FloatViewService;
import com.tihi.uiautomator.IShellCmdListener;
import com.tihi.uiautomator.ScreenCap;
import com.tihi.uiautomator.eventmsg.FloatViewDismissMsg;
import com.tihi.uiautomator.eventmsg.UpdateFloatViewMsg;
import com.tihi.util.AppUtils;
import com.tihi.util.Preferences;
import com.tihi.xml.XmlTreeParser;

/**
 * MIUI系统，设置里打开 悬浮框 限制才可以
 * @author duantihi
 * @date 2016-1-30 下午1:11:30
 */
public class MainActivity extends BaseActivity implements OnClickListener{
//	private Button startBtn;
	private TextView deviceInfo;
	private View helpView;
	private ToastExitHelper toastExitHelper;
	
	@Override
	protected int getLayout() {
		return R.layout.activity_main;
	}
	
	@Override
	protected void onCreate(@Nullable Bundle arg0) {
		super.onCreate(arg0);
		FloatViewService.startService();
		App.getAppEventBus().register(this);
		toastExitHelper = new ToastExitHelper();
//		LogUtil.log(AppUtils.getDeviceInfo());
		
//		UiDevice uiDevice;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		FloatViewMgr.instance().show();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		FloatViewService.stopService();
		
		App.getAppEventBus().unregister(this);
	}
	
	private XmlTreeParser xmlParser;
	@Override
	protected void initViews() {
		initYouMiAd();
//		startBtn = (Button) findViewById(R.id.start);
		deviceInfo = (TextView) findViewById(R.id.deviceInfo);
		helpView = findViewById(R.id.helpBtn);
//		((TextView)(findViewById(R.id.helpText))).setText("?");
		
		initDeviceInfo();
//		startBtn.setOnClickListener(this);
		findViewById(R.id.ctlBg).setOnClickListener(this);
		helpView.setOnClickListener(this);
		
		xmlParser = new XmlTreeParser(MainActivity.this);
		
		initBg();
//		addGuideView();
	}
	
	private void initBg() {
		ImageView bgImg = (ImageView) findViewById(R.id.mainActImg);
//		Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.main_bg);
//		StackBlurManager blurManager = new StackBlurManager(bm);
//		blurManager.process(5);
//		if(blurManager.returnBlurredImage() != null && 
//				!blurManager.returnBlurredImage().isRecycled()){
//			bgImg.setImageBitmap(blurManager.returnBlurredImage());
//		}
		AnimationSet set = (AnimationSet) AnimationUtils.loadAnimation(this, R.anim.main_act_img_anim);
		bgImg.startAnimation(set);
	}
	
	private void initYouMiAd() {
		// 实例化广告条
		AdView adView = new AdView(this, AdSize.FIT_SCREEN);
		// 获取要嵌入广告条的布局
		LinearLayout adLayout=(LinearLayout)findViewById(R.id.adLayout);
		// 将广告条加入到布局中
		adLayout.addView(adView);
	}
	
	private void initDeviceInfo() {
		StringBuffer sb = new StringBuffer();
		DisplayMetrics metrics = AppUtils.getDeviceDisplay();
		
		sb.append("设备信息：\r\n");
		sb.append("ScreenSize: " + metrics.widthPixels + "x" + metrics.heightPixels + "\r\n");
		sb.append("Density: " + metrics.density + "\r\n");
		sb.append("DPI: " + metrics.densityDpi);
		deviceInfo.setText(sb.toString());
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ctlBg:
//			updateBtnStatus(true);
			//FloatViewService接收消息
			App.getAppEventBus().post(new UpdateFloatViewMsg(false));
			break;
		case R.id.helpBtn:
			HelpActivity.startAct(MainActivity.this);
			FloatViewMgr.instance().dismiss();
			break;

		default:
			break;
		}
	}
	
	/**
	 * 截屏测试
	 */
	private void screenCapTest() {
		new ScreenCap(new IShellCmdListener() {
			
			@Override
			public void onResult(boolean success) {
				AppUtils.toast("截屏： " + Boolean.toString(success));
			}
		}).cap();
	}
	
	private void xmlTest() {
		xmlParser.xmlParse();
	}
	
	/**
	 * 按钮状态变化
	 */
	private void updateBtnStatus(boolean isReverse) {
		if(FloatViewMgr.instance().isShowing()) {
			if(isReverse) {
				setBtnTxt("显示");
			}else {
				setBtnTxt("隐藏"); //不会走到该路径
			}
		}else {
			if(isReverse) {
				setBtnTxt("隐藏");
			}else {
				setBtnTxt("显示");
			}
		}
	}
	
	private void setBtnTxt(String msg) {
//		startBtn.setText(msg);
	}
	
	/**
	 * 悬浮窗消失， FloatViewService发出
	 * @param msg
	 */
	public void onEventMainThread(FloatViewDismissMsg msg) {
//		updateBtnStatus(false);
	}
	
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.main, menu);
//        return true;
//    }

//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        int id = item.getItemId();
//        if (id == R.id.action_settings) {
//            return true;
//        }
//        return super.onOptionsItemSelected(item);
//    }
    
    private long firstClickTime = 0;
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
    	switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			long secTime = System.currentTimeMillis();
			if(secTime - firstClickTime > 2000) {
				toastExitHelper.show();
				firstClickTime = secTime;
				return true;
			}else {
				onBackPressed();
				toastExitHelper.cancel();
			}
			break;

		default:
			break;
		}
    	return super.onKeyDown(keyCode, event);
	}

	@Override
	protected String getTagForUmeng() {
		return "主界面";
	}
	
	private void addGuideView() {
		View rootView = getWindow().getDecorView().findViewById(R.id.actBg);
		if(rootView == null) return;
		if(Preferences.instance().getGuideShowed()) return;
		
		ViewParent viewParent = rootView.getParent();
		final FrameLayout frameLayout = (FrameLayout) viewParent;
		final ImageView guideImage = new ImageView(this);
		
		FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
		guideImage.setLayoutParams(layoutParams);
		guideImage.setScaleType(ScaleType.FIT_XY);
		guideImage.setImageResource(R.drawable.main_bg1);
		guideImage.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				frameLayout.removeView(guideImage);
				Preferences.instance().setGuideShowed();
			}
		});
		frameLayout.addView(guideImage);
	}
}
